package com.example.treehole.ui.component

import androidx.compose.foundation.gestures.detectVerticalDragGestures
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.material3.pulltorefresh.PullToRefreshDefaults
import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.pointerInput
import com.example.treehole.ui.theme.backCyan
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RefreshBox(
    modifier: Modifier = Modifier,
    isRefreshing:MutableState<Boolean>,
    onRefresh:suspend ()->Unit,
    content:@Composable ()->Unit
) {
    val scope = rememberCoroutineScope()

    val refreshState = rememberPullToRefreshState()

    PullToRefreshBox(
        isRefreshing = isRefreshing.value,
        state = refreshState,
        onRefresh = {
            scope.launch {
                isRefreshing.value = true
                delay(1500)
                onRefresh()
                isRefreshing.value = false
            }
        },
        modifier = modifier
            .fillMaxSize()
            .pointerInput(Unit){
                detectVerticalDragGestures { change, dragAmount ->
                    if(dragAmount>0){
                        change.consume()
                    }
                }
            },
        indicator = {
            PullToRefreshDefaults.Indicator(
                isRefreshing = isRefreshing.value,
                state = refreshState,
                color = backCyan,
                modifier = Modifier
                    .align(Alignment.TopCenter)
            )
        }
    ) {
        content()
    }
}